<template>
  <div class="virtual-scroll-container">
    <div
      class="virtual-scroll-list"
      :style="{ height: containerHeight + 'px' }"
      @scroll="handleScroll"
      ref="scrollContainer"
    >
      <div :style="{ height: totalHeight + 'px' }" class="scroll-placeholder"></div>
      <div
        class="virtual-list"
        :style="{ transform: `translateY(${offsetY}px)` }"
      >
        <div
          v-for="item in visibleItems"
          :key="item.id"
          class="list-item"
          :style="{ height: itemHeight + 'px' }"
        >
          {{ item.content }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'VirtualScroll',
  data() {
    return {
      items: Array.from({ length: 10000 }, (_, index) => ({
        id: index,
        content: `项目 ${index + 1}`
      })),
      containerHeight: 300,
      itemHeight: 50,
      visibleCount: 10,
      scrollTop: 0
    };
  },
  computed: {
    totalHeight() {
      return (this.items && this.items.length) ? this.items.length * this.itemHeight : 0;
    },
    startIndex() {
      return Math.floor(this.scrollTop / this.itemHeight);
    },
    endIndex() {
      return Math.min(this.startIndex + this.visibleCount, this.items.length);
    },
    visibleItems() {
      return this.items.slice(this.startIndex, this.endIndex);
    },
    offsetY() {
      return this.startIndex * this.itemHeight;
    }
  },
  methods: {
    handleScroll(event) {
      this.scrollTop = event.target.scrollTop;
    }
  }
};
</script>

<style scoped>
.virtual-scroll-container {
  background: #333;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.virtual-scroll-list {
  overflow-y: auto;
  position: relative;
  background-color: #333;
  border: 1px solid #444;
  border-radius: 4px;
}

.virtual-scroll-list::-webkit-scrollbar {
  width: 12px;
  background-color: #2d2d2d;
  border-radius: 6px;
}

.virtual-scroll-list::-webkit-scrollbar-track {
  background-color: #2d2d2d;
  border-radius: 6px;
}

.virtual-scroll-list::-webkit-scrollbar-thumb {
  background-color: #555;
  border-radius: 6px;
  border: 2px solid #2d2d2d;
}

.virtual-scroll-list::-webkit-scrollbar-thumb:hover {
  background-color: #777;
}

.virtual-scroll-list::-webkit-scrollbar-corner {
  background-color: #2d2d2d;
}

.scroll-placeholder {
  position: absolute;
  width: 100%;
}

.virtual-list {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}

.list-item {
  display: flex;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid #444;
  box-sizing: border-box;
  color: #e0e0e0;
  transition: background-color 0.2s;
}

.list-item:hover {
  background-color: #3a3a3a;
}

.list-item:last-child {
  border-bottom: none;
}
</style>